package com.wmh.baseservice.robot.tools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.robot.entity.RobotApiUri;
import com.wmh.baseservice.robot.entity.RobotInfo;
import com.wmh.baseservice.robot.entity.RobotRes;
import com.wmh.baseservice.robot.exception.MyRequestException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author 青石
 */
@Component
public class MyHttpUtil {
    public static String PREFIX = "http://";
    public static String COLON = ":";
    /**
     * 获取错误响应中状态代码的正则表达式
     */
    public static Pattern ERR_CODE_PATTERN = Pattern.compile("<title>([\\S\\s]*?)</title>");

    @Resource
    private RestTemplate rest;

    @Resource
    private Map<String, RobotApiUri> robotApiMap;


    /**
     * 对于机器的post 请求 , 如果状态码不正确 或 发生异常则设置机器状态为掉线状态
     */
    public RobotRes post(String addr, String port, String uri, JSONObject params, Object... uriParam) {
        /* 得到url */
        String url = PREFIX + addr + COLON +
                port + uri;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        /* 设置请求对象 */
        HttpEntity request = new HttpEntity<>(params, headers);
        RobotRes robotRes = null;
        try {
            LogUtil.info("MyHttpUtil => post => url : {} ", url);
            ResponseEntity<String> response = rest.postForEntity(url, request, String.class, uriParam);
            robotRes = JSON.parseObject(response.getBody(), RobotRes.class);
            if (robotRes.toString().length() <= 5000) {
                LogUtil.info("MyHttpUtil => post => res : {} ", robotRes);
            }else{
                LogUtil.info("MyHttpUtil => post => res : {} {}",robotRes.getCode(),robotRes.getMessage());
            }
            return robotRes;
        } catch (MyRequestException ex) {
            LogUtil.error("post => ex : {}", ex.getMessage());
            return new RobotRes().setMessage(ex.getMessage());
        } catch (ResourceAccessException e) {
            LogUtil.error("机器连接失败 URL : {}", url);
            return new RobotRes().setMessage("机器连接失败");
        }
    }

    /**
     * 对于机器发起 post 请求重载
     *
     * @param robot    机器对象
     * @param uriName  接口名称
     * @param params   请求参数
     * @param uriParam uri 参数
     */
    public RobotRes post(RobotInfo robot, String uriName, JSONObject params, Object... uriParam) {
        return post(robot.getRobotIp(), robot.getFlaskPort(), robotApiMap.get(uriName).getUri(), params, uriParam);
    }

}
